﻿using System;
using System.Collections;
using NHibernate;
using NHibernate.Cfg;
using System.Collections.Generic;

namespace Business
{
    public class Users
    {
        private ISessionFactory _sessionFactory;
        public Users()
        {
            _sessionFactory = DataObjects.Service.SessionFactory.GetInstance().GetNHibernateFactory();
        }
        
        public ArrayList List()
        {
            ArrayList arrRet = new ArrayList();
            using (ISession session = _sessionFactory.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                arrRet = (ArrayList)session.CreateCriteria(typeof(DataObjects.Users)).List();
                tx.Commit();
            }
            return arrRet;
        }
        public DataObjects.Users GetObjectByPK(string userId)
        {
            ArrayList arrTemp = new ArrayList();
            using (ISession session = _sessionFactory.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                IQuery query = session.CreateSQLQuery("select top 1 * from Users where User_ID =?").AddEntity(typeof(DataObjects.Users));
                query.SetString(0, userId);
                arrTemp = (ArrayList)query.List();
                tx.Commit();

                if (arrTemp.Count > 0)
                {
                    return (DataObjects.Users)arrTemp[0];
                }
                return null;
            }
        }

        //code insert - update - delete 
        public void Insert(DataObjects.Users oUser)
        {
            using (ISession session = _sessionFactory.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                session.Save(oUser);
                tx.Commit();			        
            }
        }
        public void Update(DataObjects.Users oUser)
        {
            using (ISession session = _sessionFactory.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                session.Update(oUser);
                tx.Commit();		        
            }
        }
        public void DeleteByPK(string userId)
        {
            using (ISession session = _sessionFactory.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                DataObjects.Users oUser = (DataObjects.Users)session.Load(typeof(DataObjects.Users), userId);
                session.Delete(oUser);
                tx.Commit();
            }
        }
    }
}
